package com.wondertek.common.config;

import cn.hutool.core.util.StrUtil;
import com.wondertek.common.constant.SysConstant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

/**
 * @author: gongjiangtao
 * @date: 2024/8/2 21:30
 * @Description: i18n国际化配置
 * @Version: 1.0
 */
@Configuration
public class I18nConfig {

    @Bean
    public LocaleResolver localeResolver() {
        return new I18nLocaleResolver();
    }

    /**
     * 获取请求头国际化信息
     */
    static class I18nLocaleResolver implements LocaleResolver {
        @Override
        public @NonNull Locale resolveLocale(@NonNull HttpServletRequest request) {
            Locale locale = Locale.CHINA;
            String language = request.getHeader(SysConstant.ACCEPTLANGUAGE);
            if (StrUtil.isNotBlank(language)) {
                String[] splitLanguage = language.split("_");
                if (splitLanguage.length > 1) {
                    locale = Locale.of(splitLanguage[0], splitLanguage[1]);
                }
            }
            return locale;
        }

        @Override
        public void setLocale(@NonNull HttpServletRequest request, HttpServletResponse response, Locale locale) {

        }
    }
}
